package com.eascs.brand.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.controller.BaseMasterViewController;
import com.eascs.admin.common.excel.ExcelService;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.app.dao.PageResult;
import com.eascs.brand.entity.O2oBrandEntity;
import com.eascs.brand.entity.O2oPartnerEntity;
import com.eascs.brand.form.O2oBranPage;
import com.eascs.brand.service.O2oBrandService;
import com.eascs.brand.service.O2oPartnerService;
import com.eascs.common.doc.excel.DefaultRowWriteHandler;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.file.FileTypeConstants;
import com.eascs.partner.entity.DealerPartnerEntity;
import com.eascs.partner.service.JxsPartnerService;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.AjaxConfirmButton;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.site.view.button.ShowButtonFilter;
import com.eascs.tag.MenuTag;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.service.sys.SysPermissionService;
import com.eascs.workflow.common.vo.ModelResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/brand")
public class O2oBrandController extends BaseMasterViewController  {
	
	@Reference
	SysPermissionService sysPermissionService;
	
	@Autowired
	O2oLoanapplyService o2oLoanapplyService;
	
	@Autowired
	O2oBrandService brandService;
	
	@Autowired
	O2oPartnerService partnerService;
	
	@Autowired
	private JxsPartnerService jxsPartnerService;
	
	@Value("${web.crm.url}")
	private String crmUrl;
	
	@Autowired
	private BaseUtils baseUtils;
	
	@Reference
	SysOrgService sysOrgService;
	
	/**
	 * 品牌信息查询页面
	 * @param branForm
	 * @return
	 */
	@RequestMapping("/index")
	public String index(O2oBranPage branForm) {
		branForm.setPageSize(10);
		String o2ourl = "/brand/index";
		String downloadurl="/brand/download";
		String brandName = branForm.getBrandName() == null ? "" : branForm.getBrandName();
		String hostProvince = branForm.getHostProvince() == null ? "" : branForm.getHostProvince();
		String createTime = branForm.getCreateTime() == null ? "" : branForm.getCreateTime();
		String createEndTime = branForm.getCreateEndTime() == null ? "" : branForm.getCreateEndTime();
		String Status = branForm.getStatus() == null ? "" : branForm.getStatus();
		o2ourl = UrlUtil.appendUrl(o2ourl, "brandName", brandName);
		o2ourl = UrlUtil.appendUrl(o2ourl, "hostProvince", hostProvince);
		o2ourl = UrlUtil.appendUrl(o2ourl, "createTime", createTime);
		o2ourl = UrlUtil.appendUrl(o2ourl, "createEndTime", createEndTime);
		o2ourl = UrlUtil.appendUrl(o2ourl, "Status", Status);
		o2ourl = o2ourl + "&pageIndex=";
		downloadurl=UrlUtil.appendUrl(downloadurl, "brandName", brandName);
		downloadurl=UrlUtil.appendUrl(downloadurl, "hostProvince", hostProvince);
		downloadurl=UrlUtil.appendUrl(downloadurl, "createTime", createTime);
		downloadurl=UrlUtil.appendUrl(downloadurl, "createEndTime", createEndTime);
		downloadurl=UrlUtil.appendUrl(downloadurl, "Status", Status);
		PageResult<Object[]> pageResult = brandService.getBrandPage(branForm);
		String titles[] = { "品牌名称", "品牌编码", "主办省份", "所属行业","创建时间","状态" };
		SelectDataOption[] selectDataOptions = { null, null, null, new SelectDataOption("vocation"),null,new SelectDataOption("parWFStutus")};
		//详情
		Button detailButton = ButtonHelper.createOpenButton("详情", "/brand/detail?parameter=");// parameter
		/*//添加厂家合作方
		Button addPartnerButton = ButtonHelper.createAjaxButton("添加厂家合作方", "/rpartner/view_add?brandId=", "addPartner");
		addPartnerButton.setShowButtonFilter(new ShowButtonFilter() {
			@Override
			public boolean filter(Object param) {
				Object[] params = (Object[]) param;
				Object wfstate=params[6];
				if ("0".equals(wfstate +"")) 
					return true;
				else
					return false;
			}
			
		});
		// 添加经销商合作方
		Button addJxsPartnerButton = ButtonHelper.createOpenButton("添加经销商合作方", "/jxsPartner/choosePartner?brandId=", "addJxsPartner");
		addJxsPartnerButton.setShowButtonFilter(new ShowButtonFilter() {
			@Override
			public boolean filter(Object param) {
				Object[] params = (Object[]) param;
				Object wfstate=params[6];
				if ("0".equals(wfstate +"")) 
					return true;
				else
					return false;
			}
		});*/
		//删除
		Button delete = ButtonHelper.createAjaxConfirmButton("删除", "/rbrand/deleteBrand?parameter=", "editBrand");
		delete.setShowButtonFilter(new ShowButtonFilter(){
			@Override
			public boolean filter(Object param) {
				Object[] params = (Object[]) param;
				Object wfstate=params[6];
				if ("-1".equals(wfstate+"") || "3".equals(wfstate+"")) 
					return true;
				else
					return false;
			}
		});
		//发起流程
		Button startFlow = ButtonHelper.createAjaxButton("发起流程", "/rbrand/startFlow?parameter=", "startBrandFlow");// parameter为合作方id
		startFlow.setShowButtonFilter(new ShowButtonFilter() {
			@Override
			public boolean filter(Object param) {
				Object[] params = (Object[]) param;
				Object wfstate=params[6];
				if ("-1".equals(wfstate + "") || "3".equals(wfstate + ""))
					return true;
				else
					return false;
			}
		});

		//编辑
		Button edit = ButtonHelper.createAjaxButton("编辑", "/rbrand/view_up?parameter=", "editBrand");// parameter为合作方id
		User user = UserHolder.getUser();
		edit.setShowButtonFilter(new ShowButtonFilter() {
			@Override
			public boolean filter(Object param) {
				Object[] params = (Object[]) param;
				Object wfstate=params[6];
				Object operatorId=params[7];
				if ("-1".equals(wfstate + "") || "3".equals(wfstate + "")) {
					if (user.getNo().equals(operatorId + "") || user.isSuperAdministrator()) {
						return true;
					}
				} else if ("0".equals(wfstate + "")) {
					ModelResult<Boolean> result = sysPermissionService.checkAuth(user.getNo(), "ZBPPSH");
					if (result.isSuccess() && result.getModel()) {
						return true;
					}
				}
				return false;
			}
		});
		//Button[] morButtons = new Button[] { detailButton, addPartnerButton,addJxsPartnerButton, delete, startFlow, edit};
		Button[] morButtons = new Button[] { detailButton, delete, startFlow, edit};
		PaginationInfo o2oPagingInfo = new PaginationInfo(pageResult, titles, o2ourl);
		o2oPagingInfo.setBuildPagingNavigation(true);
		o2oPagingInfo.setMoreButtons(morButtons);
		o2oPagingInfo.setSelectDataOptions(selectDataOptions);
		o2oPagingInfo.setFirstRenderColumnIndex(1);
		List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
		ViewContext.put("ActOrgEntitys", orgProvince);
		ViewContext.put("vo", branForm);
		ViewContext.put("Status", branForm.getStatus());
		ViewContext.put("o2oPagingInfo", o2oPagingInfo);
		ViewContext.put("downloadurl", downloadurl);
		return "/brand/index";
	}

	/**
	 * @Description:
	 * 				<p>
	 *               根据品牌id查询品牌详情信息
	 *               </p>
	 * @author CXW
	 * @date 2016年11月16日 上午10:02:33
	 * @version V1.0
	 */
	@RequestMapping("/detail")
	public String getEntityById(String parameter) {
		O2oBrandEntity brandEntityById = brandService.queryBrandEntityById(parameter).getModel();
		queryDataList(parameter, FileTypeConstants.BRAND_TYPE_RPMENT);
		String agreeUrl = baseUtils.getApprovalAgreeUrl(parameter, "", ProcessTemplate.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("parameter", parameter);
		ViewContext.put("brandEntityById", brandEntityById);
		User user = UserHolder.getUser();
		int wfStatus = brandEntityById.getWfStatus();
		ModelResult<Boolean> result = sysPermissionService.checkAuth(user.getNo(), "ZBPPSH");
		if ("-1".equals(wfStatus + "") || "-3".equals(wfStatus + "") ) {
			if (user.getNo().equals(wfStatus) || user.isSuperAdministrator()) {
				ViewContext.put("isEdit", "isEdit");
			}
		} else if ("0".equals(wfStatus + "")) {
			if ( result.isSuccess() && result.getModel()) {
				ViewContext.put("isEdit", "isEdit");
			}
		}
		return "/brand/detail";
	}
	@RequestMapping("/view_model")
	public String vieWDetail(String parameter) {
		queryDataListFile(parameter, FileTypeConstants.PARTNER_TYPE_RPMENT, "detail");
		queryDataListPicture(parameter, FileTypeConstants.PARTNER_TYPE_PICTURE, "detail");
		queryDataListEvidence(parameter, FileTypeConstants.PARTNER_TYPE_EVIDENCE, "detail");
		O2oPartnerEntity o2oPartnerEntity = partnerService.getEntityById(parameter);
		ViewContext.put("vo", o2oPartnerEntity);
		ViewContext.put("crmUrl", crmUrl);

		O2oBrandEntity brand = brandService.queryBrandEntityById(o2oPartnerEntity.getBrandId()).getModel();
		ViewContext.put("brand", brand);
		return "/brand/detail_model";
	}	
	
	@RequestMapping("/view_workflow_model")
	public String viewWorkflowDetail(String parameter, String approvalStatus) {
		queryDataListFile(parameter, FileTypeConstants.PARTNER_TYPE_RPMENT, "detail");
		queryDataListPicture(parameter, FileTypeConstants.PARTNER_TYPE_PICTURE, "detail");
		queryDataListEvidence(parameter, FileTypeConstants.PARTNER_TYPE_EVIDENCE, "detail");
		O2oPartnerEntity o2oPartnerEntity = partnerService.getEntityById(parameter);
		ViewContext.put("vo", o2oPartnerEntity);
		ViewContext.put("crmUrl", crmUrl);
		ViewContext.put("approvalStatus", approvalStatus);
		return "/brand/workflow_model";
	}
	
	/**
	 * 经销商合作方
	 * @param parameter
	 * @return
	 */
	
	@RequestMapping("/jxs_view_workflow_model")
	public String jxsViewWorkflowDetail(String parameter, String approvalStatus) {
		queryDataListFile(parameter, FileTypeConstants.JXS_PARTNER_TYPE_RPMENT, "detail");
		queryDataListPicture(parameter, FileTypeConstants.JXS_PARTNER_TYPE_PICTURE, "detail");
		queryDataListEvidence(parameter, FileTypeConstants.JXS_PARTNER_TYPE_EVIDENCE, "detail");
		DealerPartnerEntity dealerPartnerEntity = jxsPartnerService.getEntityById(parameter);
		List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
		if(orgProvince!=null&&orgProvince.size()>0){
			for (int i = 0; i < orgProvince.size(); i++) {
				ActOrgEntity actOrgEntity = orgProvince.get(i);
				if(dealerPartnerEntity.getOrgProvinceId().equals(actOrgEntity.getOrgId())){
					ViewContext.put("ActOrgEntity", actOrgEntity.getOrgName());
				}
			}
		}
		ViewContext.put("currentUser1", dealerPartnerEntity.getOperator());
		ViewContext.put("vo", dealerPartnerEntity);
		ViewContext.put("crmUrl", crmUrl);
		ViewContext.put("approvalStatus", approvalStatus);
		ViewContext.put("batchClassification", dealerPartnerEntity.getBatchClassification());
		return "/partner/jxs_workflow_model";
	}
	
	/**
	 * 品牌信息详情模板
	 * @param parameter
	 * @param isEdit
	 * @return
	 */
	@RequestMapping("/to_model")
	public String toModel(String parameter, String isEdit) {
		ModelResult<O2oBrandEntity> brandEntityById = brandService.queryBrandEntityById(parameter);
		queryDataList(parameter, FileTypeConstants.BRAND_TYPE_RPMENT);
		ViewContext.put("brandEntity", brandEntityById.getModel());
		ViewContext.put("isEdit", isEdit);
		ViewContext.put("parameter", parameter);
		return "/brand/brand_model";
	}
	/**
	 * 附件
	 * @param loanapplyNo
	 * @param code
	 */
	public void queryDataList(String loanapplyNo, String code) {
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + code + "'");
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null,
				ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("pageResult", paginationInfo);// 个人附件
	}
	
	public void queryDataListFile(String loanapplyNo, String code, String detailFlag) {
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + code + "'");
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null, ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		if (!"detail".equals(detailFlag)) {
			AjaxConfirmButton[] dealButton = null;
			dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
			paginationInfo.setMoreButtons(dealButton);
		}
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("pageResult", paginationInfo);// 个人附件
	}
	public void queryDataListPicture(String loanapplyNo, String code, String detailFlag) {
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + code + "'");
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null, ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		if (!"detail".equals(detailFlag)) {
			AjaxConfirmButton[] dealButton = null;
			dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
			paginationInfo.setMoreButtons(dealButton);
		}
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("pageResultPicture", paginationInfo);// 个人附件
	}
	public void queryDataListEvidence(String loanapplyNo, String code, String detailFlag) {
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + code + "'");
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null, ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		if (!"detail".equals(detailFlag)) {
			AjaxConfirmButton[] dealButton = null;
			dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
			paginationInfo.setMoreButtons(dealButton);
		}
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("pageResultEvidence", paginationInfo);// 个人附件
	}

	@RequestMapping("/download")  //根据查询导出品牌信息，否则默认导出全部
	public void downloadBrandInfo(O2oBranPage branForm, HttpServletResponse httpServletResponse,
			HttpServletRequest request) {
		branForm.setPageSize(Integer.MAX_VALUE);
		PageResult<Object[]> pageResult = brandService.getBrandInfo(branForm);
		String path = O2oBrandController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/brand-model.xls").toString();
		OutputStream os = null;
		try {
			String outfile = "品牌信息.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			DefaultRowWriteHandler defaultRowWriteHandler = new DefaultRowWriteHandler(pageResult.getData());
			ExcelApiHelper.writeHandle(httpServletResponse.getOutputStream(),
					O2oBrandController.class.getResourceAsStream("/excelTemplate/brand-model.xls"),
					defaultRowWriteHandler);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
			os.close();
		} catch (Exception e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}
	public String saveBrandInfo(List<Object[]> data) {
		// 模板
		String soucreFileName = "/excelTemplate//brand-model.xls";
		// 输出路径
		String path = O2oBrandController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/Brand.xls").toString();

		int col = 8;
		// 需要统计的列
		int[] arr = {};
		String title = "品牌信息";
		// 开始的表格，行，列
		int sheetIndex = 0;
		int rowIndex = 1;
		int columnIndex = 0;
		// 生产excel
		new ExcelService().writeByDate(soucreFileName, outPath, col, arr, Arrays.asList(title), sheetIndex, rowIndex, columnIndex, data);
		// 存放的文件的文件夹
		return path + "/" + outPath;
	}
	@Override
	public void preHandle() {
		// TODO Auto-generated method stub
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "brandCode");
	}
	
}
